/* globals Chart:false, feather:false */



// custom
let unfinishedQueryButton = null;
let unfinishedQueryForm = null;
let unfinishedExportButton = null;

let doneQueryButton = null;
let doneQueryForm = null;
let doneExportButton = null;

let globalQueryDataStr = null;
let globalQueryOrder = 'ascend';

let globalUsers = null;

let menuUserButton = null;
let menuHomeButton = null;
let chart1View = null;
let chart2View = null;
let chart3View = null;

$(function () {
  // 图标替换
  feather.replace()
  // 初始化图标

  // acquire charts
  // $.ajax({
  //   url: '/initCharts',
  //   contentType: 'application/json',
  //   method: 'GET',
  //   success: [function (data, textStatus, jqXHR) {
  //     // console.log(data);
  //     initChart(data);
  //
  //   }],
  //   error: [function (jqXHR, textStatus, errorThrown) {
  //     console.log("init Chart failure");
  //   }]
  // });

  // init unfinished Query
  unfinishedQueryButton = $('#unfinishedQueryButton');
  unfinishedQueryForm = $('#unfinishedQueryForm');
  unfinishedExportButton = $('#unfinishedExportButton');
  unfinishedQueryButton.click(function (event) {
    let inputList = unfinishedQueryForm.find('*').filter(':input');
    let valueList = {};

    inputList.each(function () {
      // if ($(this).attr('type') === 'radio') {
      //   if ($(this).prop('checked') === true) {
      //     valueList[$(this).attr('name')] = $(this).val();
      //   }
      // } else {
      //   valueList[$(this).attr('name')] = $(this).val();
      // }
      valueList[$(this).attr('name')] = $(this).val();

    });

    // query unfinished users
    $.ajax({
      url: '/user/queryUnSign',
      data: JSON.stringify(valueList),
      contentType: 'application/json',
      method: 'POST',
      success: [function (data, textStatus, jqXHR) {
        // console.log(data);

        createTable($('#unfinishedQueryTableContainer'), data.data, 'unfinishedQueryTable');
        // globalQueryDataStr = JSON.stringify(data);
        globalUsers = valueList;
      }],
      error: [function (jqXHR, textStatus, errorThrown) {
        console.log("query unfinished users data failure");
      }]
    });

  });

  // init done Query
  doneQueryButton = $('#doneQueryButton');
  doneQueryForm = $('#doneQueryForm');
  doneExportButton = $('#doneExportButton');
  doneQueryButton.click(function (event) {
    let inputList = doneQueryForm.find('*').filter(':input');
    let valueList = {};

    inputList.each(function () {
      // if ($(this).attr('type') === 'radio') {
      //   if ($(this).prop('checked') === true) {
      //     valueList[$(this).attr('name')] = $(this).val();
      //   }
      // } else {
      //   valueList[$(this).attr('name')] = $(this).val();
      // }
      valueList[$(this).attr('name')] = $(this).val();

    });

    // query done users
    $.ajax({
      url: '/answer/condition',
      data: JSON.stringify(valueList),
      contentType: 'application/json',
      method: 'POST',
      success: [function (data, textStatus, jqXHR) {
        // console.log(data);

        createTable($('#doneQueryTableContainer'), data.data, 'doneQueryTable');
        globalQueryDataStr = JSON.stringify(data.data);
      }],
      error: [function (jqXHR, textStatus, errorThrown) {
        console.log("query done users data failure");
      }]
    });

  });


  menuUserButton = $('#v-pills-users-tab');
  menuUserButton.click(function (event) {
    // acquire users and admin
    $.ajax({
      url: '/user/allUsers',
      contentType: 'application/json',
      method: 'GET',
      success: [function (data, textStatus, jqXHR) {
        // console.log(data);
        // createTable($('#adminTableContainer'), data, 'adminTable');
        createTable($('#usersTableContainer'), data.data, 'usersTable');

      }],
      error: [function (jqXHR, textStatus, errorThrown) {
        console.log("get users data failure");
      }]
    });
    // $.ajax({
    //   url: '/getAdmin',
    //   contentType: 'application/json',
    //   method: 'GET',
    //   success: [function (data, textStatus, jqXHR) {
    //     // console.log(data);
    //     // createTable($('#adminTableContainer'), data, 'adminTable');
    //     createTable($('#adminTableContainer'), data, 'adminTable');
    //
    //   }],
    //   error: [function (jqXHR, textStatus, errorThrown) {
    //     console.log("get admin data failure");
    //   }]
    // });
  });

  // menuHomeButton = $('#v-pills-home-tab');
  // menuHomeButton.click((event) => {
  //   // acquire charts
  //   $.ajax({
  //     url: '/initCharts',
  //     contentType: 'application/json',
  //     method: 'GET',
  //     success: [function (data, textStatus, jqXHR) {
  //       // console.log(data);
  //       updateChart(data);
  //
  //     }],
  //     error: [function (jqXHR, textStatus, errorThrown) {
  //       console.log("init Chart failure");
  //     }]
  //   });
  // });

  unfinishedExportButton.click(function (event) {
    let url = '/user/unSignExcelDownload?'+`username=${globalUsers.username}&department=${globalUsers.department}&name=${globalUsers.name}&major=${globalUsers.major}`;
    window.open(url);
    // $.ajax({
    //   url: '/user/unSignExcelDownload',
    //   contentType: 'application/json',
    //   data: globalUsers,
    //   method: 'POST',
    //   success: [function (data, textStatus, jqXHR) {
    //     // console.log(data);
    //     // createTable($('#adminTableContainer'), data, 'adminTable');
    //     // createTable($('#adminTableContainer'), data, 'adminTable');
    //     console.log(data);
    //   }],
    //   error: [function (jqXHR, textStatus, errorThrown) {
    //     console.log("export users data failure");
    //   }]
    // });

  });
});

// function queryResultToTable(arr) {
//   let count = Math.ceil(arr.length / 10);
//   let insertList = [];
//   let buttonList = [];
//   let queryTable = $('#queryTable');
//   let queryNav = $('#page-nav');

//   queryTable.remove('tbody');
//   queryNav.empty();

//   if (count > 5) {
//     //显示 超过50条，请直接下载Excel
//     alert('结果过多，请直接导出Excel');
//   } else {
//     for (let i = 0; i < count; i++) {
//       let tbody = $(`<tbody class="tab-pane fade" role="tabpanel" aria-labelledby=page-${i + 1}-tab></tbody>`);
//       let button = $(`<button type="button" class="btn btn-outline-primary" id="page-${i + 1}-tab" data-bs-toggle="tab"
//       data-bs-target="#page-${i + 1}" role="tab" aria-controls="page-${i + 1}" aria-selected="true">${i + 1}</button>`);
//       let subInsertList = [];
//       for (let j = i * 10; j < arr.length; j++) {
//         let item = $(`<tr><th scope="row"></th><td>${arr[j]}</td><td>${arr[j]}</td><td>${arr[j]}</td></tr>`);
//         subInsertList.push(item);
//       }
//       tbody.append(subInsertList);
//       if (i === 0) {
//         tbody.addClass("show active");
//         button.addClass("active");
//       }

//       insertList.push(tbody);
//       buttonList.push(button);
//     }
//     queryTable.append(insertList);
//     queryNav.append(buttonList);
//   }
// }

// 创建表格
function createTable(container, arr, tableName) {
  if (arr.length === 0) {
    container.empty();
    console.log('No results');
  } else {


    let page = Math.ceil(arr.length / 10);
    let table = $(`<table id=${tableName} class="table table-striped table-sm table-hover tab-content"></table>`);
    let nav = $('<nav><div class="nav nav-tabs justify-content-center" role="tablist"></div></nav>');
    // create header
    let props = Object.getOwnPropertyNames(arr[0]);
    let thead = $('<thead></thead>');
    let head_row = $('<tr></tr>');
    for (let i = 0; i < props.length; i++) {
      switch (props[i]) {
        case 'date': {
          let th = $(`<th scope="col">${props[i].toUpperCase()}</th>`);
          th.click(function (event) {
            let data = JSON.parse(globalQueryDataStr);
            if (globalQueryOrder === 'ascend') {
              data.sort((a, b) => (new Date(b.date)).getTime() - (new Date(a.date)).getTime());
              globalQueryOrder = 'descend';
            } else {
              data.sort((a, b) => (new Date(a.date)).getTime() - (new Date(b.date)).getTime());
              globalQueryOrder = 'ascend';
            }
            createTable($('#doneQueryTableContainer'), data, 'doneQueryTable');
            globalQueryDataStr = JSON.stringify(data);
          })
          head_row.append(th);
          break;
        }
        default: head_row.append($(`<th scope="col">${props[i].toUpperCase()}</th>`));
      }
    }
    thead.append(head_row);

    // create body content and nav
    let bodyList = [];
    let buttonList = [];
    for (let i = 0; i < page; i++) {
      let tbody = $(`<tbody id='${tableName}-page-${i + 1}' class="tab-pane fade" role="tabpanel" aria-labelledby='${tableName}-page-${i + 1}-tab'></tbody>`);
      let subInsertList = [];
      for (let j = i * 10; j < arr.length && j < (i + 1) * 10; j++) {
        let item = $(`<tr class="${arr[j]['lock'] ? 'bg-secondary':""}"></tr>`);
        for (let k = 0; k < props.length; k++) {
          switch (props[k]) {
            case 'admin': {
              let button = `<button class="btn btn-outline-primary btn-sm">${arr[j][props[k]] ? '撤销管理员' : '设为管理员'}</button>`;
              item.append($(`<td>${button}</td>`));
              break;
            }
            case 'lock': {
              let button = $(`<button class="btn btn-outline-primary btn-sm" data-enabled="${arr[j][props[k]]?1:0}" data-username="${arr[j]['username']}">${arr[j][props[k]] ? '解锁' : '锁定'}</button>`);
              button.click((event) => {

                let btn = $(event.target);

                $.ajax({
                  url: `/user/modifyEnabled/${btn.attr('data-username')}/${btn.attr('data-enabled')}`,
                  contentType: 'application/json',
                  method: 'GET',
                  success: [function (data, textStatus, jqXHR) {
                    // console.log(data);
                    if (data.code === 0) {
                      btn.attr('data-enabled', data.data["enabled"]);
                      btn.text(data.data["str"]);
                      let parent = btn.parent().parent();
                      if (data.data["enabled"] === 1) {
                        parent.addClass("bg-secondary");
                      } else {
                        parent.removeClass("bg-secondary");
                      }
                    }

                  }],
                  error: [function (jqXHR, textStatus, errorThrown) {
                    console.log("update user failure");
                  }]
                });
              });
              item.append($(`<td></td>`).append(button));
              break;
            }
            case 'date': {
              let date = new Date(arr[j][props[k]]);
              item.append($(`<td>${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日</td>`));
              break;
            }
            // case 'username': {
            //   let link = $(`<button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#model">${arr[j][props[k]]}</button>`);
            //   link.click((event) => {
            //     // acquire a user
            //     $.ajax({
            //       url: `/user/${arr[j][props[k]]}`,
            //       contentType: 'application/json',
            //       method: 'GET',
            //       success: [function (data, textStatus, jqXHR) {
            //         let ul = $(`<ul class="list-group"></ul>`);
            //         let keys = Object.getOwnPropertyNames(data.data);
            //         for (let i=0; i<keys.length; i++) {
            //           let li = $(`<li class="list-group-item"><div class='ms-2'><span class='fw-bold'>${key[i]}</span>${data.data[key[i]]}</div></li>`);
            //           ul.append(li);
            //         }
            //         $('#model-body').append(ul);
            //
            //       }],
            //       error: [function (jqXHR, textStatus, errorThrown) {
            //         console.log("get user detail data failure");
            //       }]
            //     });
            //   });
            //
            //   item.append($('<td></td>').append(link));
            //   break;
            // }
            default: item.append($(`<td>${arr[j][props[k]]}</td>`));
          }

        }

        subInsertList.push(item);
      }
      tbody.append(subInsertList);

      // create nav button
      let button = $(`<button type="button" class="btn btn-outline-primary" id="${tableName}-page-${i + 1}-tab" data-bs-toggle="tab"
      data-bs-target="#${tableName}-page-${i + 1}" role="tab" aria-controls="${tableName}-page-${i + 1}" aria-selected="false">${i + 1}</button>`);

      // active if it is the first page
      if (i === 0) {
        tbody.addClass("show active");
        button.addClass("active");
        button.attr('aria-selected', true);
      }
      // add List
      bodyList.push(tbody);
      buttonList.push(button);
    }
    table.append(thead).append(bodyList);
    nav.children().append(buttonList);

    container.empty().append(table).append(nav).removeClass('d-none');

  }



}

function initChart(chartData) {
  // chart1: 今天各学院的打卡人数
  let chart1 = $('#chart1');
  const chart1Labels = chartData[0].labels;
  const chart1Data = {
    labels: chart1Labels,
    datasets: [{
      label: '今天各学院的打卡人数',
      data: chartData[0].data,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 205, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(54, 162, 235, 0.2)',

      ],
      borderColor: [
        'rgb(255, 99, 132)',
        'rgb(255, 159, 64)',
        'rgb(255, 205, 86)',
        'rgb(75, 192, 192)',
        'rgb(54, 162, 235)',

      ],
      borderWidth: 1
    }]
  };
  const chart1Config = {
    type: 'bar',
    data: chart1Data,
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    },
  };
  chart1View = new Chart(chart1, chart1Config);

  // chart2: 昨天各学院未打卡人数
  let chart2 = $('#chart2');
  const chart2Labels = chartData[1].labels;
  const chart2Data = {
    labels: chart2Labels,
    datasets: [{
      label: '昨天各学院未打卡人数',
      data: chartData[1].data,
      fill: true,
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  };
  const chart2Config = {
    type: 'line',
    data: chart2Data,
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    },
  };
  chart2View = new Chart(chart2, chart2Config);

  // chart3: 上一周未打卡人数变化
  let chart3 = $('#chart3');
  const chart3Labels = chartData[2].labels;
  const chart3Data = {
    labels: chart3Labels,
    datasets: [{
      label: '上一周未打卡人数',
      data: chartData[2].data,
      fill: false,
      borderColor: 'rgb(255, 159, 64)',
      tension: 0.1
    }]
  };
  const chart3Config = {
    type: 'line',
    data: chart3Data
  };
  chart3View = new Chart(chart3, chart3Config);


}

function updateChart(chartData) {
  chart1View.data.labels = chartData[0].labels;
  chart1View.data.datasets[0].data = chartData[0].data;
  chart1View.update();
  
  chart2View.data.labels = chartData[1].labels;
  chart2View.data.datasets[0].data = chartData[1].data;
  chart2View.update();

  chart3View.data.labels = chartData[2].labels;
  chart3View.data.datasets[0].data = chartData[2].data;
  chart3View.update();


}